package com.jizhangben.controller;

import com.jizhangben.pojo.UserPojo;
import com.jizhangben.utils.RandomValidateCode;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import com.jizhangben.service.UserService;

import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("views/login.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 点击登录的时候 获取到用户的参数
        String userId = req.getParameter("userId");
        String loginPassword = req.getParameter("loginPassword");
        // 图形验证码  比较 是在 登录之前
        // 比较图形验证码
        String userCode = req.getParameter("loginCode"); // 用户输入的图形验证码
        // 从session中获取图形验证码
        HttpSession session0 = req.getSession();
        String sessionCode = (String) session0.getAttribute(RandomValidateCode.RANDOMVALIDATECODE);
        if (!sessionCode.equalsIgnoreCase(userCode)) {
            req.setAttribute("errorMsg", "图形验证码不正确，请重新输入!");
            req.getRequestDispatcher("views/login.jsp").forward(req, resp);
            return;
        }
        // 在调用业务逻辑层
        UserPojo userPojo = userService.login(userId, loginPassword);
        if (userPojo == null) {
            // 用户名称或者密码错误!
            req.setAttribute("errorMsg", "用户名称或者是密码错误!");
            req.getRequestDispatcher("views/login.jsp").forward(req, resp);
            return;
        }
        // 能够db中查询到对象 登录成功了  将用户数据存放在session中
        HttpSession session = req.getSession();
        session.setAttribute("user", userPojo);
        // 在转发到首页（重定向到首页）
        resp.sendRedirect(req.getContextPath()+"/account");
    }
}
